package com.core.framework.tools.xml;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.core.log.Log;


public class Config {
    private static XmlGlobalFactory xmlg = null;
    public static Map<String, Object> loadConfig(Map<String, Object> configData, String configString) throws IOException {
        if (xmlg == null) {
            //1.输出静态配置
            xmlg = new XmlGlobalFactory();
            xmlg.setIgnoreRootElement(true);
            xmlg.getLoadNameSpace().add("http://noe.xdf.cn/schema/global");
        }
        //2.输出动态配置
        Map<String, Object> configMap_2 = xmlg.createMap("utf-8", new Object[] { ResourcesUtil.getResourceAsStream(configString) });
        for (String key : configMap_2.keySet()) {
            String $key = key.trim().toLowerCase();
            configData.put($key, configMap_2.get(key));
        }
        return configData;
    }
    /*======================================================================配置*/
    private static Global globalConfig   = null;
    private static File   configFile     = null;
    private static long   lastCheckTime  = 0;
    private static long   lastUpdateTime = 0;
    private static long   checkSeepTime  = 15 * 1000; //15秒
    /**获取配置*/
    public static Global getGlobal() {
        try {
            URL url = ResourcesUtil.getResource("ttt.xml");
            if ("file".equals(url.getProtocol()) == true) {
                //1.File对象
                if (configFile == null) {
                    configFile = new File(url.toURI());
                    lastCheckTime = 0;
                    lastUpdateTime = 0;
                }
                //2.时间检测
                Date date = new Date();
                if (lastCheckTime + checkSeepTime < date.getTime()) {
                    if (lastUpdateTime != configFile.lastModified()) {
                        lastUpdateTime = configFile.lastModified();
                        globalConfig = null;
                    }
                    lastCheckTime = date.getTime();
                }
            }
            //
            if (globalConfig == null) {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                //1.输出配置
                dataMap = loadConfig(dataMap, "ttt.xml");
                
               
                //2.建立配置文件Mapping机制
//                IAttribute<String> configMap_4 = ResourcesUtil.getPropertys("config-mapping.properties");
//                for (String key : configMap_4.getAttributeNames()) {
//                    String $propxyKey = key.trim().toLowerCase();
//                    String $key = configMap_4.getAttribute(key).trim().toLowerCase();
//                    String value = (String) dataMap.get($key);
//                    //org.noe.framework.util.log.Log.debug("$$$ mapping.. " + $propxyKey + "=" + $key + " , value=" + value);
//                    if (value == null)
//                        throw new RuntimeException("mapping.. " + $propxyKey + "=" + $key + " 出错，值为空");
//                    dataMap.put($propxyKey, value.trim());
//                }
                //3.创建不同机构的配置装载器。
                globalConfig = Global.newInterInstance(dataMap);
                globalConfig.disableCaseSensitive();
                Log.info("输出配置...");
//                for (String key : globalConfig.getAttributeNames())
//                    org.noe.framework.util.log.Log.debug("att=" + key);
            }
        } catch (Exception e) {
        	Log.error(e.getMessage());
            throw new RuntimeException("装载配置文件出错.", e);
            //                ResourceBundle bundle = ResourceBundle.getBundle("config");
            //                Map<String, String> map = new HashMap<String, String>();
            //                Enumeration<String> en = bundle.getKeys();
            //                while (en.hasMoreElements()) {
            //                    String key = en.nextElement();
            //                    map.put(key, bundle.getString(key));
            //                }
            //                globalConfig = Global.newInterInstance(new TransformToAttribute(map));
        }
        return globalConfig;
    } 
    
    public static Global getGlobal(String xml) {
        try {
            URL url = ResourcesUtil.getResource("config.xml");
            if ("file".equals(url.getProtocol()) == true) {
                //1.File对象
                if (configFile == null) {
                    configFile = new File(url.toURI());
                    lastCheckTime = 0;
                    lastUpdateTime = 0;
                }
                //2.时间检测
                Date date = new Date();
                if (lastCheckTime + checkSeepTime < date.getTime()) {
                    if (lastUpdateTime != configFile.lastModified()) {
                        lastUpdateTime = configFile.lastModified();
                        globalConfig = null;
                    }
                    lastCheckTime = date.getTime();
                }
            }
            if (globalConfig == null) {
                Map<String, Object> dataMap = new HashMap<String, Object>();
                //1.输出配置
                dataMap = loadConfig(dataMap, "string-config.xml");
                dataMap = loadConfig(dataMap, "static-config.xml");
                dataMap = loadConfig(dataMap, "config.xml");
                dataMap = loadConfig(dataMap, "xxx.xml");
                //dataMap = loadConfig(dataMap, "ttt.xml");
               
 
                //3.创建不同机构的配置装载器。
                globalConfig = Global.newInterInstance(dataMap);
                globalConfig.disableCaseSensitive();

            }
        } catch (Exception e) {
            throw new RuntimeException("装载配置文件出错.", e);
        }
        return globalConfig;
    }
    /** 把配置转换成map */
    public static Map<String, String> toMap() {
        Map<String, String> map = new HashMap<String, String>();
        Global global = getGlobal();
        String[] names = global.getAttributeNames();
        for (String name : names)
            map.put(name, global.getString(name));
        return map;
    }
    public static String getString(String key) {
        //默认值是 null.
    	
        return getGlobal().getString(key, null);
    }
    
//    public static String getString(String key,String xml) {
//        //默认值是 null.
//        return getGlobal(xml).getString(key, null);
//    }
    
    public static String getString(String key, String defaultValue) {
        //默认值是 null.
        return getGlobal().getString(key, defaultValue);
    }
    public static Class<?> getClassType(String key) {
        //默认值是 null.
        String classname = getGlobal().getString(key, null);
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(classname);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
    public static int getInteger(String string) {
        //默认值是 0.
        return getGlobal().getInteger(string, 0);
    }
    public static boolean getFlag(String string) {
        //默认值是 false.
        return getGlobal().getBoolean(string, false);
    }
    public static String getFilePath(String string) {
        //默认值是 false.
        return getGlobal().getFilePath(string, "");
    }
    public static String getDirectoryPath(String string) {
        //默认值是 false.
        return getGlobal().getDirectoryPath(string, "");
    }
    /**获取一个字符串信息*/
    public static String getMessage(String keyGroup, String key) {
        return getGlobal().getString("Strings." + keyGroup + ".String." + key);
    }
}